package com.bafa.services;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;

import com.bafa.dbcache.*;
import com.bafa.jdbc.DBAccess;
import com.bafa.jdbc.QueryObject;
import com.bafa.jdbc.UpdateObject;
import com.bafa.objects.Match;
import com.bafa.objects.Round;
import com.bafa.objects.Message;
import com.bafa.objects.team.Team;
import com.bafa.objects.team.TeamSeasonStats;
import com.bafa.objects.schema.*;
import com.bafa.objects.season.Division;
import com.bafa.objects.season.Season;
import com.bafa.tables.Keys;

public class SeasonServices {

	public static Message confirmRound(int matchId,int seasonId, int teamA, int teamB, boolean refresh){
		Message message = new Message();
		DBAccess db = new DBAccess();
		QueryObject roundQuery = new QueryObject("roundsformat");
		roundQuery.addWhereAndField("MatchId",matchId+"");
		
		try{
			// round has been confirmed as ready
			UpdateObject updateRound = new UpdateObject();
			updateRound.addField("Confirmed",1);
			db.update(roundQuery,updateRound);
			
			confirmTeamForRound(matchId, seasonId, teamA, teamB,refresh);
			
			message.addMessage("Round confirmed");
		}catch(Exception e){
			
		}finally{
			
			db.disconnect();
		}
		return message;
	}

	public static Message addLeagueRules(int seasonId, int divisionId, int promoted, int relegated, int numPlayEachOther)throws Exception{
		Message message = new Message();
		DBAccess db = new DBAccess();
	
		
		try{
			// match is updated
			QueryObject query = new QueryObject("leaguerules");
			UpdateObject update = new UpdateObject();
			update.addField("seasonid", seasonId);
			update.addField("divisionid",divisionId);
			update.addField("promoted",promoted);
			update.addField("relegated",relegated);
			update.addField("numtoplayeachteam",numPlayEachOther);
			db.insert(query,update);
			ObjectFactory factory = new ObjectFactory();
			LeagueRules rules = factory.createLeagueRules();
			rules.setNumberOfTeamsPromoted(promoted);
			rules.setNumberOfTeamsRelegated(relegated);
			rules.setNumberOfTimesEachTeamPlays(numPlayEachOther);
			
			
			message.addMessage("League Rules successfully added");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			//LeagueCache.refreshSeason(seasonId);
			db.disconnect();
		}
		return message;
	}
	public static Message confirmTeamForRound(int matchId,int seasonId, int teamA, int teamB,boolean refresh){
		Message message = new Message();
		DBAccess db = new DBAccess();
	
		
		try{
			// match is updated
			QueryObject query = new QueryObject("matches");
			query.addWhereAndField("ID",""+matchId);
			UpdateObject update = new UpdateObject();
			if(teamA>0)update.addField("TeamA",teamA);
			if(teamB>0)update.addField("TeamB",teamB);
			db.update(query,update);
			
			
			message.addMessage("Done");
		}catch(Exception e){
			
		}finally{
			try{
				Team teamAObj = RetrieveServices.getTeam(""+teamA);
				Team teamBObj = RetrieveServices.getTeam(""+teamA);
			}catch(Exception e){
				
			}
			
			db.disconnect();
		}
		return message;
	}
	
	public static Season createSeason(String season, int year, String cupLeague, boolean isSwitchedOn,int numDivisions){
		ObjectFactory factory = new ObjectFactory();
		DBAccess db = new DBAccess();
		
		Message message = new Message();
		QueryObject queryObj = new QueryObject("season");
		
		Season seasonObj = new Season();
		
		try{
			seasonObj.setId(GrabSeasons.getCurrentSeasonId()+1);
			GrabSeasons.setCurrentSeasonId(GrabSeasons.getCurrentSeasonId()+1);
			seasonObj.setName(season);
			seasonObj.setYear(year);
			seasonObj.setLeague((cupLeague.equalsIgnoreCase("league")));
			seasonObj.setSwitchedOn(isSwitchedOn);
			seasonObj.setCompleted(false);
			for(int i=0;i<numDivisions;i++){
				Division division = new Division();
				division.setDivision(i+1);
				division.setSeasonId(seasonObj.getId());
				seasonObj.enterDivision(division);
			}
			db.storeSeason(seasonObj);
			GrabSeasons.addSeason(seasonObj);
			message.addMessage("Season created successfully");
			
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
			return seasonObj;
		}
	}

	public static Message switchSeasonOn(int seasonId){
		Message message = new Message();
		DBAccess db = new DBAccess();
			QueryObject queryObj = new QueryObject("season");
			queryObj.addWhereAndField("ID",""+seasonId);
			UpdateObject updateObj = new UpdateObject();
			updateObj.addField("SwitchOn",1);
			try{
				db.update(queryObj,updateObj);
				message.addMessage("Season has been switched on ready for use");
				//LeagueCache.refreshSeason(seasonId);
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				db.disconnect();
			}
			return message;
		
	}

	public static Message switchSeasonOff(int seasonId){
		Message message = new Message();
		DBAccess db = new DBAccess();
			QueryObject queryObj = new QueryObject("season");
			queryObj.addWhereAndField("ID",""+seasonId);
			UpdateObject updateObj = new UpdateObject();
			updateObj.addField("SwitchOn",0);
			try{
				db.update(queryObj,updateObj);
				message.addMessage("Season has been switched off");
				//LeagueCache.refreshSeason(seasonId);
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				db.disconnect();
			}
			return message;
		
	}

	public static void addTeamToSeason(int seasonId, int division, int teamId){
		
		Season season = RetrieveServices.getSeason(seasonId+"");
		((Division)season.getDivisions().get(division)).addTeams(teamId);
		TeamSeasonStats seasonStats = new TeamSeasonStats(teamId);
		RetrieveServices.getTeam(teamId+"").getStats().addSeasonStat(seasonId,seasonStats);
		
		DBAccess db = new DBAccess();
		
		try{
			db.updateSeason(season);
			db.updateTeam(RetrieveServices.getTeam(teamId+""));
		}catch(Exception e){
			
		}
		
		/*DBAccess db = new DBAccess();
		QueryObject query = new QueryObject(Keys.LEAGUE);
	    ObjectFactory factory = new ObjectFactory();
		UpdateObject update = new UpdateObject();
		update.addField(Keys.LEAGUE_SEASONID,seasonId);
		update.addField(Keys.LEAGUE_Division,division);
		update.addField(Keys.LEAGUE_TeamID,teamId);
		
		try{
			db.insert(query,update);
			com.bafa.objects.schema.Season season = RetrieveCache.getSeason(seasonId);
                        if(season.getDivision().size()<division){
                            com.bafa.objects.schema.Division divisionObj = factory.createDivision();
                            divisionObj.setDivision(division);
                            divisionObj.setSeasonId(seasonId);
                            season.getDivision().add(divisionObj);
                        }
                        
                        season.getDivision().get(division-1).getTeam().add(teamId);
			
			TeamSeason teamSeason = factory.createTeamSeason();
			teamSeason.setDivision(division);
			teamSeason.setSeasonId(seasonId);
			//com.bafa.objects.schema.Team team = RetrieveCache.getTeam(teamId);
			//team.getTeamStats().getTeamSeason().add(teamSeason);
			
			
			//db.updateTeam(team);
			//GrabTeams.addTeam(team);
		
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
		}*/
	}
/*
    public static void addTeamToSeason(Season season, int division, int teamId){
            DBAccess db = new DBAccess();
            QueryObject query = new QueryObject(Keys.LEAGUE);
            
            UpdateObject update = new UpdateObject();
            update.addField(Keys.LEAGUE_SEASONID,season.getId());
            update.addField(Keys.LEAGUE_Division,division);
            update.addField(Keys.LEAGUE_TeamID,teamId);
            
            try{
                    db.insert(query,update);
                    
                    //season.getDivision().get(division-1).getTeam().add(teamId);
                    ObjectFactory factory = new ObjectFactory();
                    TeamSeason teamSeason = factory.createTeamSeason();
                    teamSeason.setDivision(division);
                    //teamSeason.setSeasonId(season.getI);
                    //com.bafa.objects.schema.Team team = RetrieveCache.getTeam(teamId);
                   //team.getTeamStats().getTeamSeason().add(teamSeason);
                    
                    
                   // db.updateTeam(team);
                    //GrabTeams.addTeam(team);
                    
            }catch(Exception e){
                    e.printStackTrace();
            }finally{
                    db.disconnect();
            }
    }
  */  
	public static Message createNextRound(int seasonId, String name, boolean cup){
		Message message = new Message();
		/* Get Previous round*/
		int previousRound = 0;
		Round round =null;// DisplayServices.getLastRound(""+seasonId,cup);
		if(round!=null)
			previousRound = round.getID();
		/* ******************* */
		DBAccess db = new DBAccess();
		QueryObject query = new QueryObject("rounds");
		UpdateObject update = new UpdateObject();
		update.addField("SeasonId",seasonId);
		update.addField("Name",name);
		update.addField("Previous",previousRound);
		if(cup)update.addField("Cup",1);
		else update.addField("Cup",0);
	
		try{
			db.insert(query,update);
			//LeagueCache.refreshSeason(seasonId);
			message.addMessage("You have successfully created the next round: "+name);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
		}
		
		return message;
	}

public static String getDivisionName(int divisionId, int seasonId){
    DBAccess db = new DBAccess();
   String name = "";
   try{
   name =  db.retrieveDivisionName(divisionId,seasonId);
    }catch(Exception e){
        e.printStackTrace();
    }
    
    return name;
}

public static void setDivisionNames(int seasonId, String[] names){
    
}
}
